<template>
  <div :class="getClass" :style="getStyle">
    <Upload :fileList="[]" :accept="getAccept" :disabled="getDisabled" :beforeUpload="handleUpload">
      <div
        :class="`${prefixCls}-image-wrapper`"
        :style="{ ...getImageWrapperStyle, ...getWrapperStyle }"
      >
        <div :class="`${prefixCls}-image-mask`" :style="getImageWrapperStyle" v-if="!getDisabled">
          <Icon
            icon="ant-design:cloud-upload-outlined"
            :size="getIconWidth"
            :style="getImageWrapperStyle"
          />
        </div>
        <img :src="sourceValue" v-if="sourceValue" alt="image" />
      </div>
    </Upload>
  </div>
</template>
<script lang="ts" setup>
  import { computed, CSSProperties, unref, ref, watchEffect, watch } from 'vue';
  import { Upload } from 'ant-design-vue';
  import { useDesign } from '@/hooks/web/useDesign';
  import { useI18n } from '@/hooks/web/useI18n';
  import { useMessage } from '@/hooks/web/useMessage';
  import Icon from '@/components/Icon/Icon.vue';

  defineOptions({ name: 'ImageSelector' });
  const props = defineProps({
    width: { type: [String, Number], default: '200px' },
    accept: { type: [String], default: 'image/*' },
    maxSize: { type: Number, default: 2 },
    border: { type: [String, Number], default: '1px' },
    radius: { type: [String, Number], default: '0%' },
    value: { type: String },
    disabled: { type: Boolean, default: false },
  });
  const emit = defineEmits(['update:value', 'change']);

  const sourceValue = ref(props.value || '');
  const { prefixCls } = useDesign('selector-image');
  const { t } = useI18n();
  const { createMessage } = useMessage();

  const getDisabled = computed(() => props.disabled || false);
  const getWidth = computed(() => `${props.width}`.replace(/px/, '') + 'px');
  const getIconWidth = computed(() => parseInt(`${props.width}`.replace(/px/, '')) / 2 + 'px');
  const getAccept = computed(() => props.accept);
  const getMaxSize = computed(() => props.maxSize);

  const getBorder = computed(() => `${props.border}`.replace(/px/, '') + 'px');
  const getRadius = computed(() => `${props.radius}`.replace(/%/, '') + '%');

  const getClass = computed(() => [prefixCls]);
  const getStyle = computed((): CSSProperties => ({ width: unref(getWidth) }));
  const getImageWrapperStyle = computed(
    (): CSSProperties => ({ width: unref(getWidth), height: unref(getWidth) }),
  );
  const getWrapperStyle = computed(
    (): CSSProperties => ({
      borderWidth: unref(getBorder),
      // borderStyle:'solid',
      // borderColor: '#d9d9d9',
      borderRadius: unref(getRadius),
      background: 'rgba(255, 255, 255, 0.1)',
    }),
  );

  watchEffect(() => {
    sourceValue.value = props.value || '';
  });

  watch(
    () => sourceValue.value,
    (v: string) => {
      emit('update:value', v);
    },
  );

  /** 处理图片上传 */
  async function handleUpload(file: File) {
    // const isJpgOrPng =
    //   file.type === 'image/jpeg' ||
    //   file.type === 'image/png' ||
    //   file.type === 'image/bmp' ||
    //   file.type === 'image/gif' ||
    //   file.type === 'image/x-icon';
    // if (!isJpgOrPng) {
    //   createMessage.error(t('component.upload.acceptUpload', [getAccept.value]));
    //   return isJpgOrPng;
    // }
    const fileSizeMB = file.size / 1024 / 1024;
    const isLtMB = fileSizeMB < getMaxSize.value;
    if (!isLtMB) {
      createMessage.error(t('component.upload.maxSize', [getMaxSize.value]));
      return isLtMB;
    }
    const reader = new FileReader();
    reader.readAsDataURL(file);
    sourceValue.value = '';
    let filename = '';
    reader.onload = function (e) {
      sourceValue.value = (e.target?.result as string) ?? '';
      filename = file.name;
      emit('change', { source: sourceValue.value, filename, file });
      // console.log('handleUpload', { source: sourceValue.value, filename, file });
    };
    return false;
  }
</script>

<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-selector-image';

  .@{prefix-cls} {
    display: inline-block;
    text-align: center;

    &-image-wrapper {
      overflow: hidden;
      // border: 1px solid @border-color-base;
      border-style: solid;
      border-color: @border-color-base;
      background: @component-background;
      cursor: pointer;
      // border-radius: 50%;

      img {
        width: 100%;
      }
    }

    &-image-mask {
      position: absolute;
      width: inherit;
      height: inherit;
      transition: opacity 0.4s;
      border: inherit;
      border-radius: inherit;
      opacity: 0;
      background: rgb(0 0 0 / 40%);
      cursor: pointer;

      ::v-deep(svg) {
        margin: auto;
      }
    }

    &-image-mask:hover {
      opacity: 40;
    }
  }
</style>
